import requests
import redis
import os

DEPOT_NAME = os.environ.get('DEPOT_NAME')
PROJECT_WEB_URL = os.environ.get('PROJECT_WEB_URL')
redis_client = redis.Redis(host='www.xdan.ai', port=6379, password='xdan_redis_passwd', db=3)
notified_commits_key = f"notified_commits:{DEPOT_NAME}:"

def is_notified(commit_sha):
    return redis_client.sismember(notified_commits_key, commit_sha)

def mark_notified(commit_sha):
    redis_client.sadd(notified_commits_key, commit_sha)

def getDepotId():
    response = requests.post(git_api_url, headers=git_headers, json=request_body_depot_id)
    if response.status_code == 200:
        data = response.json()
        depots = data.get('Response', {}).get('DepotData', {}).get('Depots', [])
        if len(depots) == 1:
            return depots[0]['Id']
        else:
            print("Error: Depot not found.")
            raise Exception("Depot not found.")
    else:
        print("Error:", response.status_code)
        raise Exception("Error getting depot id.")

git_api_url = "https://e.coding.net/open-api"
feishu_webhook_url = "https://www.feishu.cn/flow/api/trigger-webhook/ce8ccca34792dde2b71cce40cdcd3638"
auth_token = "81e4ad07c84de9d911e49535cf789729e344114c"
title = f"{DEPOT_NAME} 发版通知"

git_headers = {
    "Authorization": f"token {auth_token}",
    "Content-Type": "application/json"
}
request_body_depot_id = {
    "Action": "DescribeTeamDepotInfoList",
    "ProjectName": "",
    "DepotName": DEPOT_NAME,
    "PageNumber": 1,
    "PageSize": 500
}
request_body_commit_log = {
    "Action": "DescribeGitCommits",
    "DepotId": getDepotId(),
    "PageNumber": 1,
    "PageSize": 500,
    "Ref": "master",
    "Path": "",
    "StartDate": "",
    "EndDate": ""
}

response = requests.post(git_api_url, headers=git_headers, json=request_body_commit_log)

if response.status_code == 200:
    response_data = response.json()
    new_commits = []

    for commit in response_data.get('Response', {}).get('Commits', []):
        commit_sha = commit['Sha']
        if is_notified(commit_sha):
            break
        new_commits.append(commit)
    commits_str = ""
    if new_commits:
        for commit in new_commits:
            message = commit['FullMessage'].replace('\n', '')
            author = commit['AuthorName']
            sha = commit['Sha']
            commits_str += f"**{message}**  [{sha}]({PROJECT_WEB_URL}/d/{DEPOT_NAME}/git/commit/{sha})  *by {author}*\n"

        final_data = {"data": commits_str, "title": title}

        webhook_response = requests.post(feishu_webhook_url, headers={"Content-Type": "application/json"},
                                         json=final_data)

        if webhook_response.status_code == 200:
            for commit in new_commits:
                mark_notified(commit['Sha'])
            print("Success: Data sent to Feishu webhook.")
        else:
            print(f"Error sending to Feishu webhook: {webhook_response.status_code}")
    else:
        print("No new commits to notify.")
else:
    print("Error:", response.status_code)
